set more off
set scheme s2mono

/*
Note that the following LAPOP version files are used in this .do file:

AmericasBarometer Grand Merge 2004 only (v3.0).dta
merge_dims_2006_with_uru_bra_ven_v20.dta
merge_dims_lapop_2008_22_countries_V6.dta
Merge 2010 Barometro de las Americas ARG CHI v12.DTA
Merge_2012_AmericasBarometer_25_countries_v13.dta
AmericasBarometer Grand Merge 2014 only (v3.0).dta
dirty_GM v07172017(shortr)RECODED.dta

These data files were provided to the authors by the Latin American Public Opinion Project (LAPOP). Raw data files for 
each survey year should be downloaded from https://www.vanderbilt.edu/lapop/ and placed in the same folder as this .do 
file prior to executing this .do file. LAPOP occasionally updates data files. If the files available are updated versions, 
modifications to the code below may be necessary. The end user is responsible for any modifications.

Also place countryDataBase.dta in the same folder as this .do file.

*/

* First part recodes, merges LAPOP data, and adds country level data

use "AmericasBarometer Grand Merge 2004 only (v3.0).dta", clear

gen wt_2004=wt
label var wt_2004 "Peso del pais, 2004"
gen wt1500_2004 = weight1500 
label var wt1500_2004 "Peso para darle el mismo tamano a cada pais, 2004"

saveold "AmericasBarometer Grand Merge 2004 only (v3.0b).dta", replace

use "merge_dims_2006_with_uru_bra_ven_v20.dta", clear

gen wt_2006=wt
label var wt_2006 "Peso del pais, 2006"
gen wt1500_2006 = weight1500 
label var wt1500_2006 "Peso para darle el mismo tamano a cada pais, 2006"

saveold "merge_dims_2006_with_uru_bra_ven_v20b.dta", replace

use "merge_dims_lapop_2008_22_countries_V6.dta", clear

gen wt_2008=wt
label var wt_2008 "Peso del pais, 2008"
gen wt1500_2008 = weight1500 
label var wt1500_2008 "Peso para darle el mismo tamano a cada pais, 2008"

saveold "merge_dims_lapop_2008_22_countries_V6b.dta", replace

use "Merge 2010 Barometro de las Americas ARG CHI v12.DTA", clear

gen wt_2010=wt
label var wt_2010 "Peso del pais, 2010"
gen wt1500_2010 = weight1500 
label var wt1500_2010 "Peso para darle el mismo tamano a cada pais, 2010"

saveold "Merge 2010 Barometro de las Americas ARG CHI v12b.DTA", replace

use "Merge_2012_AmericasBarometer_25_countries_v13.dta", clear

gen wt_2012=wt
label var wt_2012 "Peso del pais, 2012"
gen wt1500_2012 = weight1500 
label var wt1500_2012 "Peso para darle el mismo tamano a cada pais, 2012"

saveold "Merge_2012_AmericasBarometer_25_countries_v13b.dta", replace

use "AmericasBarometer Grand Merge 2014 only (v3.0).dta", clear
gen wt_2014=wt
label var wt_2014 "Peso del pais, 2014"
gen wt1500_2014 = weight1500 
label var wt1500_2014 "Peso para darle el mismo tamano a cada pais, 2014"

rename vb3n vb3

saveold "AmericasBarometer Grand Merge 2014 only (v3.0b).dta", replace


use "dirty_GM v07172017(shortr).dta", clear
keep if wave==2016
gen yearfielded=year
replace year=2016 if wave==2016
gen wt_2016=wt
label var wt_2016 "Peso del pais, 2016"
gen wt1500_2016 = weight1500 
label var wt1500_2016 "Peso para darle el mismo tamano a cada pais, 2016"

rename vb3n vb3

saveold "AmericasBarmeter2016Only.dta", replace

clear all

#delimit ;

local commonvars "
weight1500
pais 
year
idnum
d1
d2
d3
d4
etid
edr
ur
q1
cp6
r1 
r3 
r4 
r4a 
r5 
r6 
r7  
r8 
r12 
r14 
r15
"
;

local vars2004 "
wt1500_2004
vb3_04
guavb3
"
;

local vars2006 "
wt1500_2006
vb3
"
;

local vars2008 "
wt1500_2008
vb3
"
;

local vars2010 "
wt1500_2010
colorr
vb3
rac1c
"
;

local vars2012 "
wt1500_2012
odd
vb3
colorr
rac1ca
"
;

local vars2014 "
wt1500_2014
vb3
colorr
quintall
"
;

local vars2016 "
wt1500_2016
vb3
colorr
"
;


#delimit cr

use "AmericasBarometer Grand Merge 2004 only (v3.0b).dta"

keep `commonvars' `vars2004'

append using "merge_dims_2006_with_uru_bra_ven_v20b.dta", keep(`commonvars' `vars2006') force

append using "merge_dims_lapop_2008_22_countries_V6b.dta", keep(`commonvars' `vars2008') force

append using "Merge 2010 Barometro de las Americas ARG CHI v12b.DTA", keep(`commonvars' `vars2010') force

append using "Merge_2012_AmericasBarometer_25_countries_v13b.dta", keep(`commonvars' `vars2012') force 

append using "AmericasBarometer Grand Merge 2014 only (v3.0b).dta", keep(`commonvars' `vars2014') force

append using "AmericasBarmeter2016Only.dta", keep(`commonvars' `vars2016') force


saveold "Merge_2004_2016_reduced", replace

label drop _all

drop if pais>21   
drop if pais==0

gen d1r = d1-1
gen d2r = d2-1
gen d3r = d3-1
gen d4r = d4-1
egen mistol = rowmiss(d1r d2r d3r d4r)
egen tolr_i = rowmean(d1r d2r d3r d4r) if mistol<=2
drop mistol
label var tolr_i "Tolerance index"

gen selfetid = etid
label var selfetid "Self-identified ethnicity, corrected codings"

recode selfetid 5=7 if pais==1 & year==2004
recode selfetid 5=7 if pais==2 & year==2006
recode selfetid 5=7 if pais==8 & year==2004
recode selfetid 1110=3 1111=3 1112=3 if pais==11 & (year==2014 | year==2016)
recode selfetid 1113=7 if pais==11 & (year==2014 | year==2016)
recode selfetid 1106=7 if pais==11
recode selfetid 6=7 if pais==11
recode selfetid 5=7 if pais==15 & year==2008 
recode selfetid 2=5 if pais==15 & year==2008 
recode selfetid 5=7 if pais==15 & year==2010 
recode selfetid 2=5 if pais==15 & year==2010 
recode selfetid 6=7 if pais==15 & year==2012 
recode selfetid 1506=7 if pais==15 & (year==2014 | year==2016)
recode selfetid 6=2 if pais==16 & year==2008
recode selfetid 6=2 if pais==16 & year==2010
recode selfetid 6=2 if pais==16 & year==2012
recode selfetid 1606=2 if pais==16 & (year==2014 | year==2016)
recode selfetid 5=4

gen white=0 if selfetid~=.
recode white 0=1 if selfetid==1
label var white "White"

gen mestizo=0 if selfetid~=.
recode mestizo 0=1 if selfetid==2
label var mestizo "Mestizo"

gen indig=0 if selfetid~=.
recode indig 0=1 if selfetid==3
label var indig "Indigenous"

gen black=0 if selfetid~=.
recode black 0=1 if selfetid==4
label var black "Afro-descendant"

gen otroethn=0 if selfetid~=.
recode otroethn 0=1 if selfetid==7
label var otroethn "Other ethnicity"

gen selfetid_altVen = selfetid
recode selfetid_altVen 2=7 if pais==16 & year==2008 & etid==6
recode selfetid_altVen 2=7 if pais==16 & year==2010 & etid==6
recode selfetid_altVen 2=7 if pais==16 & year==2012 & etid==6
recode selfetid_altVen 2=7 if pais==16 & year==2014 & etid==1606

gen mestizo_altVen=0 if selfetid_altVen~=.
recode mestizo_altVen 0=1 if selfetid_altVen==2
label var mestizo_altVen "Mestizo, without Moreno"

gen otroethn_altVen=0 if selfetid_altVen~=.
recode otroethn_altVen 0=1 if selfetid_altVen==7
label var otroethn_altVen "Other ethnicity, with Moreno"


#delimit ;

local yearlist "
2010
2012
2014
2016
" ;

local countrylist "
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
21
" ;

#delimit cr

replace colorr=. if colorr>=12
gen colorRelative=.
label var colorRelative "Color Palette, Mean Centered by Country Year"
gen colorStd=.
label var colorStd "color Palette, Standardized by Country Year"
gen colorQuartile=.
label var colorQuartile "Color Quartile within Country Year"

foreach year of local yearlist {
foreach country of local countrylist {

sum colorr if year==`year' & pais==`country'
replace colorRelative=colorr-r(mean) if year==`year' & pais==`country'
replace colorStd=colorRelative/r(sd) if year==`year' & pais==`country'

xtile quartile=colorr if year==`year' & pais==`country', nq(4)
replace colorQuartile=quartile if year==`year' & pais==`country'
drop quartile
}
}


gen lighter=0
replace lighter=1 if colorRelative<=-1
replace lighter=. if colorr==.

gen darker=0
replace darker=1 if colorRelative>=1
replace darker=. if colorr==.

gen female = q1
recode female 1=0 2=1
label var female "Female"

gen cp6r = cp6
recode cp6r 4=0 3=1 1=3
label var cp6r "Religious meeting attendance"
label def cp_r 0 "Never" 3 "Once a week"
label val cp6r cp_r

gen urban = ur
recode urban 2=0 1=1
label var urban "Urban"
label def urban 0 "Rural" 1 "Urban"
label val urban urban

gen incum_voter = 0
recode incum_voter 0 =1 if vb3==1001 & year==2006 & pais==1 //Fox (PAN)
recode incum_voter 0 =1 if vb3==101 & year==2008 & pais==1  //Calderon (PAN)
recode incum_voter 0 =1 if vb3==101 & year==2010 & pais==1  //Calderon (PAN)
recode incum_voter 0 =1 if vb3==101 & year==2012 & pais==1  //Calderon (PAN)
recode incum_voter 0 =1 if vb3==101 & year==2014 & pais==1  // Pen~a Nieto (PRI)
recode incum_voter 0 =1 if vb3==101 & year==2016 & pais==1  // Pen~a Nieto (PRI)
 
recode incum_voter 0 =1 if guavb3==204 & year==2004 & pais==2 //Berger (GANA)
recode incum_voter 0 =1 if vb3==2004 & year==2006 & pais==2 //Berger (GANA)
recode incum_voter 0 =1 if vb3==201 & year==2008 & pais==2  //Alvaro Colom (UNE)
recode incum_voter 0 =1 if vb3==201 & year==2010 & pais==2  //Alvaro Colom (UNE)
recode incum_voter 0 =1 if vb3==206 & year==2012 & pais==2  //Otto Perez Molina (PP)
recode incum_voter 0 =1 if vb3==206 & year==2014 & pais==2  //Otto Perez Molina (PP)
recode incum_voter 0 =1 if vb3==201 & year==2016 & pais==2  //Jimmy Morales (FCN)

recode incum_voter 0 =1 if vb3_04==301 & year==2004 & pais==3 //Francisco Flores (ARENA)
recode incum_voter 0 =1 if vb3==3001 & year==2006 & pais==3 //Antonio Saca (ARENA)
recode incum_voter 0 =1 if vb3==301 & year==2008 & pais==3  //Antonio Saca (ARENA)
recode incum_voter 0 =1 if vb3==302 & year==2010 & pais==3  //Mauricio Funes (FMLN)
recode incum_voter 0 =1 if vb3==302 & year==2012 & pais==3  //Mauricio Funes (FMLN)
recode incum_voter 0 =1 if vb3==302 & year==2014 & pais==3  //FMLN, Party of Mauricio Funes (sitting president at time of survey) as well as Salvador Sanchez Ceren victor of 2nd round 2014 elections which were held 2 weeks before survey
recode incum_voter 0 =1 if vb3==302 & year==2016 & pais==3  //FMLN, Salvador Sanchez Ceren victor of 2nd round 2014 election

recode incum_voter 0 =1 if vb3_04==401 & year==2004 & pais==4 //Ricardo Maduro (P. Nacional), not 100% confident of coding on this
recode incum_voter 0 =1 if vb3==4001 & year==2006 & pais==4 //Manuel Zelaya (P. Liberal)
recode incum_voter 0 =1 if vb3==401 & year==2008 & pais==4  //Manuel Zelaya (P. Liberal)
recode incum_voter 0 =1 if vb3==404 & year==2010 & pais==4  //Pepe Lobo (P. Nacional)
recode incum_voter 0 =1 if vb3==404 & year==2012 & pais==4  //Pepe Lobo (P. Nacional)
recode incum_voter 0 =1 if vb3==401 & year==2014 & pais==4  //Juan Orlando Hernandez (P. Nacional)
recode incum_voter 0 =1 if vb3==401 & year==2016 & pais==4  //Juan Orlando Hernandez (P. Nacional)

recode incum_voter 0 =1 if vb3==5001 & year==2006 & pais==5 //Enrique Bolan~os (PLC)
recode incum_voter 0 =1 if vb3==502 & year==2008 & pais==5  //Daniel Ortega (FSLN)
recode incum_voter 0 =1 if vb3==502 & year==2010 & pais==5  //Daniel Ortega (FSLN)
recode incum_voter 0 =1 if vb3==502 & year==2012 & pais==5  //Daniel Ortega (FSLN)
recode incum_voter 0 =1 if vb3==502 & year==2014 & pais==5  //Daniel Ortega (FSLN)
recode incum_voter 0 =1 if vb3==502 & year==2016 & pais==5  //Daniel Ortega (FSLN)

recode incum_voter 0 =1 if vb3_04==601 & year==2004 & pais==6 //PUSC (Abel Pacheco)
recode incum_voter 0 =1 if vb3==6002 & year==2006 & pais==6 //Oscar Arias (PLN)
recode incum_voter 0 =1 if vb3==602 & year==2008 & pais==6  //Oscar Arias (PLN)
recode incum_voter 0 =1 if vb3==602 & year==2010 & pais==6  //Oscar Arias (PLN)
recode incum_voter 0 =1 if vb3==602 & year==2012 & pais==6  //Laura Chinchilla (PLN)
recode incum_voter 0 =1 if vb3==602 & year==2014 & pais==6  //PLN (Johnny Araya), party of Laura Chinchilla, who was sitting president at the time of the survey, although Luis Guillermo Solis won the presidential election while the survey was in the field and assumed office two days after completion of the survey
recode incum_voter 0 =1 if vb3==603 & year==2016 & pais==6  //PAC (Luis Guillermo Solis)

recode incum_voter 0 =1 if vb3==7003 & year==2006 & pais==7 //Martin Torrijos (PRD)
recode incum_voter 0 =1 if vb3== 703 & year==2008 & pais==7 //Martin Torrijos (PRD)
recode incum_voter 0 =1 if vb3== 702 & year==2010 & pais==7 //Ricardo Martinelli (Cambio Democratico)
recode incum_voter 0 =1 if vb3== 702 & year==2012 & pais==7 //Ricardo Martinelli (Cambio Democratico)
recode incum_voter 0 =1 if vb3== 702 & year==2014 & pais==7 //Ricardo Martinelli (Cambio Democratico)
recode incum_voter 0 =1 if vb3== 701 & year==2016 & pais==7 //Juan Carlos Varela (PAN)

recode incum_voter 0 =1 if vb3==8003 & year==2006 & pais==8 //Alvaro Uribe (Partido de la U)
recode incum_voter 0 =1 if vb3== 803 & year==2008 & pais==8 //Alvaro Uribe (Partido de la U)
recode incum_voter 0 =1 if vb3== 803 & year==2010 & pais==8 //Alvaro Uribe (Partido de la U)
recode incum_voter 0 =1 if vb3== 804 & year==2012 & pais==8 //Juan Manuel Santos (PSUN)
recode incum_voter 0 =1 if vb3== 804 & year==2014 & pais==8 //Juan Manuel Santos (PSUN)
recode incum_voter 0 =1 if vb3== 804 & year==2016 & pais==8 //Juan Manuel Santos (PSUN)

recode incum_voter 0 =1 if vb3_04==901 & year==2004 & pais==9 //Gutierrez (PSP)
recode incum_voter 0 =1 if vb3==9001 & year==2006 & pais==9 //9001=Gutierrez (PSP), victor of the 2002 election. But in 2006, Palacio was President who ascended to presidency after Gutierrez was removed (same coalition)
recode incum_voter 0 =1 if vb3== 901 & year==2008 & pais==9 //Rafael Correa (PAIS)
recode incum_voter 0 =1 if vb3== 901 & year==2010 & pais==9 //Rafael Correa (PAIS)
recode incum_voter 0 =1 if vb3== 901 & year==2012 & pais==9 //Rafael Correa (PAIS)
recode incum_voter 0 =1 if vb3== 901 & year==2014 & pais==9 //Rafael Correa (PAIS)
recode incum_voter 0 =1 if vb3== 901 & year==2016 & pais==9 //Rafael Correa (PAIS)

recode incum_voter 0 =1 if vb3==10002 & year==2006 & pais==10 //Evo Morales (MAS)
recode incum_voter 0 =1 if vb3== 1002 & year==2008 & pais==10 //Evo Morales (MAS)
recode incum_voter 0 =1 if vb3== 1002 & year==2010 & pais==10 //Evo Morales (MAS)
recode incum_voter 0 =1 if vb3== 1002 & year==2012 & pais==10 //Evo Morales (MAS)
recode incum_voter 0 =1 if vb3== 1002 & year==2014 & pais==10 //Evo Morales (MAS)
recode incum_voter 0 =1 if vb3== 1001 & year==2016 & pais==10 //Evo Morales (MAS) - this is right, coding changed

recode incum_voter 0 =1 if vb3==11002 & year==2006 & pais==11 //Alan Garcia (APRA)
recode incum_voter 0 =1 if vb3== 1102 & year==2008 & pais==11 //Alan Garcia (APRA)
recode incum_voter 0 =1 if vb3==1101 & year==2012 & pais==11  //Ollanta Humala (Gana Peru)
recode incum_voter 0 =1 if vb3==1101 & year==2014 & pais==11  //Ollanta Humala (Gana Peru)
recode incum_voter 0 =1 if vb3==1101 & year==2016 & pais==11  //Pedro Pablo Kuczynski (Peruanos por el Kambio) 

recode incum_voter 0 =1 if vb3==12001 & year==2006 & pais==12 //Nicanor Duarte (Colorado)
recode incum_voter 0 =1 if vb3== 1201 & year==2008 & pais==12 //Nicanor Duarte (Colorado)
recode incum_voter 0 =1 if vb3== 1201 & year==2010 & pais==12 //Fernando Lugo (APC)
recode incum_voter 0 =1 if vb3== 1201 & year==2012 & pais==12 //Fernando Lugo (APC)
recode incum_voter 0 =1 if vb3== 1201 & year==2014 & pais==12 //Horacio Cartes (ANR)
recode incum_voter 0 =1 if vb3== 1201 & year==2016 & pais==12 //Horacio Cartes (ANR)

recode incum_voter 0 =1 if vb3==13001 & year==2006 & pais==13 //Michelle Bachellet (PS)
recode incum_voter 0 =1 if vb3== 1301 & year==2008 & pais==13 //Michelle Bachellet (PS)
recode incum_voter 0 =1 if vb3== 1302 & year==2010 & pais==13 //Sebastian Pin~era (RN)
recode incum_voter 0 =1 if vb3== 1302 & year==2012 & pais==13 //Sebastian Pin~era (RN)
recode incum_voter 0 =1 if vb3== 1305 & year==2014 & pais==13 //Michelle Bachellet (PS) -- had just assumed presidency
recode incum_voter 0 =1 if vb3== 1305 & year==2016 & pais==13 //Michelle Bachellet (PS)

recode incum_voter 0 =1 if vb3==1401 & year==2006 & pais==14 //Tabare Vasquez (FA)
recode incum_voter 0 =1 if vb3==1401 & year==2008 & pais==14 //Tabare Vasquez (FA)
recode incum_voter 0 =1 if vb3==1401 & year==2010 & pais==14 //Jose Mujica (FA)
recode incum_voter 0 =1 if vb3==1401 & year==2012 & pais==14 //Jose Mujica (FA)
recode incum_voter 0 =1 if vb3==1401 & year==2014 & pais==14 //Jose Mujica (FA)
recode incum_voter 0 =1 if vb3==1401 & year==2016 & pais==14 //TabarÃ© VÃ¡zquez (FA)

recode incum_voter 0 =1 if vb3==1501 & year==2008 & pais==15 //Lula (PT)
recode incum_voter 0 =1 if vb3==1501 & year==2010 & pais==15 //Lula (PT)
recode incum_voter 0 =1 if vb3==1 & year==2012 & pais==15    //Dilma (PT)
recode incum_voter 0 =1 if vb3==1501 & year==2014 & pais==15 //Dilma (PT)
recode incum_voter 0 =1 if vb3==1501 & year==2016 & pais==15 //Dilma (PT)

recode incum_voter 0 =1 if vb3==1601 & year==2006 & pais==16 //Hugo Chavez (PSUV)
recode incum_voter 0 =1 if vb3==1601 & year==2008 & pais==16 //Hugo Chavez (PSUV)
recode incum_voter 0 =1 if vb3==1601 & year==2010 & pais==16 //Hugo Chavez (PSUV)
recode incum_voter 0 =1 if vb3==1601 & year==2012 & pais==16 //Hugo Chavez (PSUV)
recode incum_voter 0 =1 if vb3==1601 & year==2014 & pais==16 //Nicolas Maduro (PSUV)
recode incum_voter 0 =1 if vb3==1601 & year==2016 & pais==16 //Nicolas Maduro (PSUV)

recode incum_voter 0 =1 if vb3==1701 & year==2008 & pais==17 //Christina Fernandez (FPV)
recode incum_voter 0 =1 if vb3==1701 & year==2010 & pais==17 //Christina Fernandez (FPV)
recode incum_voter 0 =1 if vb3==1701 & year==2012 & pais==17 //Christina Fernandez (FPV)
recode incum_voter 0 =1 if vb3==1701 & year==2014 & pais==17 //Christina Fernandez (FPV)
recode incum_voter 0 =1 if vb3==1701 & year==2016 & pais==17 //Mauricio Macri (Cambiemos) 

recode incum_voter 0 =1 if vb3==21001 & year==2006 & pais==21 // Leonel Fernandez (PLD)
recode incum_voter 0 =1 if vb3==2101  & year==2008 & pais==21 // Leonel Fernandez (PLD) 
recode incum_voter 0 =1 if vb3==2101 & year==2010 & pais==21  // Leonel Fernandez (PLD)
recode incum_voter 0 =1 if vb3==2101 & year==2012 & pais==21  // Leonel Fernandez (PLD)
recode incum_voter 0 =1 if vb3==2101 & year==2014 & pais==21  //Danilo Medina (PLD)
recode incum_voter 0 =1 if vb3==2101 & year==2016 & pais==21  //Danilo Medina (PLD)


label var incum_voter "Voted for Incumbent"
label de incum_voter 1 "Yes" 0 "No"

recode r1 0=1 1=0 if pais==7 & year==2006
recode r3 0=1 1=0 if pais==7 & year==2006
recode r4 0=1 1=0 if pais==7 & year==2006
recode r4a 0=1 1=0 if pais==7 & year==2006
recode r6 0=1 1=0 if pais==7 & year==2006
recode r7 0=1 1=0 if pais==7 & year==2006
recode r8 0=1 1=0 if pais==7 & year==2006
recode r12 0=1 1=0 if pais==7 & year==2006
recode r14 0=1 1=0 if pais==7 & year==2006
recode r15 0=1 1=0 if pais==7 & year==2006
capture drop quintiles
capture drop wealthscoresquin 
ssc install sumdist, all replace
gen quintiles=.
gen wealthscoresquin=.

#delimit ;

local yearlist "
2006
2008
2010
2012
2014
2016
" ;

local countrylist "
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
21
" ;


#delimit cr


foreach country of local countrylist {

foreach year of local yearlist {


pca   r1 r3 r4 r4a r5 r6 r7 r8 r12 r14 r15 if pais==`country' & year==`year'
predict  f1`country'`year' if pais==`country' & year==`year'
sumdist f1`country'`year',  n(5) qgp(quint`country'`year')
replace quintiles=quint`country'`year' if pais==`country' & year==`year'
replace wealthscoresquin=f1`country'`year' if pais==`country' & year==`year'

}
}

**Separate calculation for Argentina which is missing in 2006 data
#delimit ;

local yearlist "
2008
2010
2012
2014
2016
" ;

local countrylist "
17
" ;


#delimit cr


foreach country of local countrylist {

foreach year of local yearlist {

pca   r1 r3 r4 r4a r5 r6 r7 r8 r12 r14 r15 if pais==`country' & year==`year'
predict  f1`country'`year' if pais==`country' & year==`year'
sumdist f1`country'`year',  n(5) qgp(quint`country'`year')
replace quintiles=quint`country'`year' if pais==`country' & year==`year'
replace wealthscoresquin=f1`country'`year' if pais==`country' & year==`year'

}
}

label variable quintiles "Quintiles of wealth"

**Making wealth vars for 2004

#delimit ;

local yearlist "
2004
" ;

local countrylist "
1
2
3
4
5
6
7
8
" ;


#delimit cr


foreach country of local countrylist {

foreach year of local yearlist {

pca   r1 r3 r4 r4a r5 r6 r7 r12 r14 r15 if pais==`country' & year==`year'
predict  f1`country'`year' if pais==`country' & year==`year'
sumdist f1`country'`year',  n(5) qgp(quint`country'`year')
replace quintiles=quint`country'`year' if pais==`country' & year==`year'
replace wealthscoresquin=f1`country'`year' if pais==`country' & year==`year'

}
}


**Calculation for Ecuador 2004
pca   r1 r3 r4 r5 r6 r7 r8 r12 r14 if pais==9 & year==2004
predict  f192004 if pais==9 & year==2004
sumdist f192004,  n(5) qgp(quint92004)
replace quintiles=quint92004 if pais==9 & year==2004
replace wealthscoresquin=f192004 if pais==9 & year==2004

**Calculation for Bolivia 2004
pca   r1 r3 r4 r5 r6 r7 r8 r12 r15 if pais==10 & year==2004
predict  f1102004 if pais==10 & year==2004
sumdist f1102004,  n(5) qgp(quint102004)
replace quintiles=quint102004 if pais==10 & year==2004
replace wealthscoresquin=f1102004 if pais==10 & year==2004

local varlist "f112006 quint12006 dec12006 f112008 quint12008 dec12008 f112010 quint12010 dec12010 f112012 quint12012 dec12012 f112014 quint12014 dec12014 f122006 quint22006 dec22006 f122008 quint22008 dec22008 f122010 quint22010 dec22010 f122012 quint22012 dec22012 f122014 quint22014 dec22014 f132006 quint32006 dec32006 f132008 quint32008 dec32008 f132010 quint32010 dec32010 f132012 quint32012 dec32012 f132014 quint32014 dec32014 f142006 quint42006 dec42006 f142008 quint42008 dec42008 f142010 quint42010 dec42010 f142012 quint42012 dec42012 f142014 quint42014 dec42014 f152006 quint52006 dec52006 f152008 quint52008 dec52008 f152010 quint52010 dec52010 f152012 quint52012 dec52012 f152014 quint52014 dec52014 f162006 quint62006 dec62006 f162008 quint62008 dec62008 f162010 quint62010 dec62010 f162012 quint62012 dec62012 f162014 quint62014 dec62014 f172006 quint72006 dec72006 f172008 quint72008 dec72008 f172010 quint72010 dec72010 f172012 quint72012 dec72012 f172014 quint72014 dec72014 f182006 quint82006 dec82006 f182008 quint82008 dec82008 f182010 quint82010 dec82010 f182012 quint82012 dec82012 f182014 quint82014 dec82014 f192006 quint92006 dec92006 f192008 quint92008 dec92008 f192010 quint92010 dec92010 f192012 quint92012 dec92012 f192014 quint92014 dec92014 f1102006 quint102006 dec102006 f1102008 quint102008 dec102008 f1102010 quint102010 dec102010 f1102012 quint102012 dec102012 f1102014 quint102014 dec102014 f1112006 quint112006 dec112006 f1112008 quint112008 dec112008 f1112010 quint112010 dec112010 f1112012 quint112012 dec112012 f1112014 quint112014 dec112014 f1122006 quint122006 dec122006 f1122008 quint122008 dec122008 f1122010 quint122010 dec122010 f1122012 quint122012 dec122012 f1122014 quint122014 dec122014 f1132006 quint132006 dec132006 f1132008 quint132008 dec132008 f1132010 quint132010 dec132010 f1132012 quint132012 dec132012 f1132014 quint132014 dec132014 f1142006 quint142006 dec142006 f1142008 quint142008 dec142008 f1142010 quint142010 dec142010 f1142012 quint142012 dec142012 f1142014 quint142014 dec142014 f1152006 quint152006 dec152006 f1152008 quint152008 dec152008 f1152010 quint152010 dec152010 f1152012 quint152012 dec152012 f1152014 quint152014 dec152014 f1162006 quint162006 dec162006 f1162008 quint162008 dec162008 f1162010 quint162010 dec162010 f1162012 quint162012 dec162012 f1162014 quint162014 dec162014 f1212006 quint212006 dec212006 f1212008 quint212008 dec212008 f1212010 quint212010 dec212010 f1212012 quint212012 dec212012 f1212014 quint212014 dec212014 f1172008 quint172008 dec172008 f1172010 quint172010 dec172010 f1172012 quint172012 dec172012 f1172014 quint172014 dec172014 f112004 quint12004 dec12004 f122004 quint22004 dec22004 f132004 quint32004 dec32004 f142004 quint42004 dec42004 f152004 quint52004 dec52004 f162004 quint62004 dec62004 f172004 quint72004 dec72004 f182004 quint82004 dec82004 f192004 quint92004 dec92004 f1102004 quint102004 dec102004 f112016 quint12016 f122016 quint22016 f132016 quint32016 f142016 quint42016 f152016 quint52016 f162016 quint62016 f172016 quint72016 f182016 quint82016 f192016 quint92016 f1102016 quint102016 f1112016 quint112016 f1122016 quint122016 f1132016 quint132016 f1142016 quint142016 f1152016 quint152016 f1162016 quint162016 f1212016 quint212016 f1172016 quint172016"

foreach var of local varlist {

capture drop `var' 

}

merge m:1 pais year using "countryDataBase.dta"
drop _merge
move country year

keep if year==2004 | year==2006 | year==2008 | year==2010 | year==2012 | year==2014 | year==2016

save "mainData.dta", replace




*Analysis

keep if dempolity>=6 // Democracies only

label var bgi_dec_fear_cent "Between Group Inequality"
label var edr "Education level"
label var otroethn "Other Ethnicity"
label var v2pepwrsoc_rev "Political Exclusion"
label var cp6r "Religious Meeting Attendance"
label var quintile "Wealth Quintile"

mixed tolr_i [pweight=weight1500] || country: , cov(independent) || country_year: , cov(independent)
estat icc

// Model 1
mixed tolr_i c.bgi_dec_fear_cent c.v2pepwrsoc_rev black indig mestizo otroethn incum_voter cp6r edr quintile female urban [pweight=weight1500] || country: , cov(independent) || country_year:, cov(independent)
estimates store model1
sum bgi_dec_fear_cent
local minbgi=round(r(min),.1)
local maxbgi=round(r(max),.1)

margins, atmeans at(bgi_dec_fear_cent=(`minbgi'(.1)`maxbgi')) post
est store bgieffect
marginsplot, ///
	plotopts(mcolor(none) lcolor(black)) recastci(rarea) ///
	ciopts(fcolor(gs15) lcolor(gs15)) level(90) ///
	title("") xtitle("") xlabel(`minbgi'(1.5)`maxbgi') ///
	xtitle("Between Group Inequality (mean-centered)") ///
	ytitle("Predicted Level of Tolerance") ///
	yline(0, lcolor(black)) ///
	graphregion(color(gs15)) scale(1.2)
graph save "bgiEffect.gph", replace
graph export "bgiEffect.pdf", as(pdf) replace

sum v2pepwrsoc_rev
local minexcl=round(r(min),.1)
local maxexcl=round(r(max),.1)
estimates restore model1
margins, atmeans at(v2pepwrsoc_rev=(`minexcl'(.1)`maxexcl')) post
est store excleffect
marginsplot, ///
	plotopts(mcolor(none) lcolor(black)) recastci(rarea) ///
	ciopts(fcolor(gs15) lcolor(gs15)) level(90) ///
	title("") xtitle("") xlabel(`minexcl'(1.5)`maxexcl') ///
	xtitle("Political Exclusion") ///
	ytitle("Predicted Level of Tolerance") ///
	yline(0, lcolor(black)) ///
	graphregion(color(gs15)) scale(1.2)
graph save "exclEffect.gph", replace
graph export "exclEffect.pdf", as(pdf) replace

// Alternative Models 1 Estimated with centered skin color:
mixed tolr_i c.bgi_dec_fear_cent v2pepwrsoc_rev colorRelative incum_voter cp6r edr quintile female urban [pweight=weight1500] || country: , cov(independent) || country_year:, cov(independent)
mixed tolr_i c.bgi_dec_fear_cent v2pepwrsoc_rev lighter darker incum_voter cp6r edr quintile female urban [pweight=weight1500] || country: , cov(independent) || country_year:, cov(independent)

// Model 2
mixed tolr_i c.bgi_dec_fear_cent##(c.indig c.black) v2pepwrsoc_rev mestizo  otroethn incum_voter cp6r edr quintile female urban [pweight=weight1500] || country: , cov(independent) || country_year: indig black, cov(independent)
estimates store model2

estimates restore model2

sum bgi_dec_fear_cent
local minbgi=round(r(min),.1)
local maxbgi=round(r(max),.1)
estimates restore model2
margins, atmeans at(bgi_dec_fear_cent=(`minbgi' `maxbgi') indig=(0 1) black=0 mestizo=0 otroethn=0) at(bgi_dec_fear_cent=(`minbgi' `maxbgi') indig=0 black=1 mestizo=0 otroethn=0) post
est store predictedbgiXethnicity
sum bgi_dec_fear_cent
local minbgi=round(r(min),.1)
local maxbgi=round(r(max),.1)
estimates restore predictedbgiXethnicity
marginsplot, ///
	plotopts(recast(line) mcolor(black) lcolor(black)) ///
	plot1opts(lpattern(dash)) plot2opts(lpattern(solid)) plot3opts(lpattern(dot)) ///
	noci ///
	title("") xtitle("Between-Group Inequality (mean-centered)") xscale(range(`minbgi'(1.5)`maxbgi')) ///
	xlabel(`minbgi'(1.5)`maxbgi') ///
	ytitle("Predicted Level of Tolerance") ///
	legend(order(1 "White" 3 "Indigenous" 2 "Afro-Descendant")) ///
	graphregion(color(gs15)) scale(1.2)
graph save "predictedBGIXethnicity.gph", replace
graph export "predictedBGIXethnicity.pdf", as(pdf) replace

mixed tolr_i bgi_dec_fear_cent c.v2pepwrsoc_rev##(c.indig c.black) mestizo  otroethn incum_voter cp6r edr quintile female urban [pweight=weight1500] || country: , cov(independent) || country_year: indig black, cov(independent)

estimates store model3

sum v2pepwrsoc_rev
local minexcl=round(r(min),.1)
local maxexcl=round(r(max),.1)
estimates restore model3
margins, atmeans at(v2pepwrsoc_rev=(`minexcl' `maxexcl') indig=(0 1) black=0 mestizo=0 otroethn=0) at(v2pepwrsoc_rev=(`minexcl' `maxexcl') indig=0 black=1 mestizo=0 otroethn=0) post
est store predictedexclXethnicity
sum v2pepwrsoc_rev
local minexcl=round(r(min),.1)
local maxexcl=round(r(max),.1)
estimates restore predictedexclXethnicity
marginsplot, ///
	plotopts(recast(line) mcolor(black) lcolor(black)) ///
	plot1opts(lpattern(dash)) plot2opts(lpattern(solid)) plot3opts(lpattern(dot)) ///
	noci ///
	title("") xtitle("Political Exclusion") xscale(range(`minexcl'(1.5)`maxexcl')) ///
	xlabel(`minexcl'(1.5)`maxexcl') ///
	ytitle("Predicted Level of Tolerance") ///
	legend(order(1 "White" 3 "Indigenous" 2 "Afro-Descendant")) ///
	graphregion(color(gs15)) scale(1.2)
graph save "predictedexclXethnicity.gph", replace
graph export "predictedesclXethnicity.pdf", as(pdf) replace

esttab model1 model2 model3 using "table1.txt", replace tex b(3) se(3) r2(3) label alignment(.) nomtitles numbers nogaps compress title("Multi-Level Models of Tolerance Toward Regime Opponents")


// Bolivia (pais==10) analysis:

gen postMorales=0
replace postMorales=1 if year>=2005
regress tolr_i postMorales##(c.indig c.white) incum_voter cp6r edr quintile female urban [pweight=weight1500] if pais==10, cluster(year)
margins, atmeans at(postMorales=(0 1) indig=(1) white=(0)) at(postMorales=(0 1) indig=(0) white=(1))  post
*margins, dydx(postMorales) atmeans at(postMorales=(0 1) indig=(1) white=(0)) at(postMorales=(0 1) indig=(0) white=(1))  post
est store moralesXeth
marginsplot, ///
	plotopts(recast(scatter) mcolor(black) lcolor(black) connect(line)) ///
	plot1opts(lpattern(dash) msymbol(T)) plot2opts(lpattern(solid) msymbol(S)) ///
	noci ///
	title("") xtitle("Post-Morales") xscale(range(-.50 1.5)) ///
	xlabel(0 "No" 1 "Yes") ///
	ytitle("Predicted Level of Tolerance") ///
	legend(order(1 "Indigenous" 2 "White")) ///
	graphregion(color(gs15)) scale(1.2)
graph save "bolivia.gph", replace
graph export "bolivia.pdf", as(pdf) replace

* Code for table showing descriptives and inclusion of each country in Model 1

estimates restore model1
predict res1, res
bysort country: tab year if res1~=.
bysort country: sum bgi_dec_fear_cent if res1~=.
bysort country: sum v2pepwrsoc_rev if res1~=.
preserve
collapse tolr_i if res1~=., by(country year)
bysort country: sum tolr_i
restore

// Subset of countries where Afro-descendant vs. Indigenous are relevant

***Code for black vs indiginous dominant group
gen blackDominant=0
replace blackDominant=1 if country=="Rep Dom"
replace blackDominant=1 if country=="Panama"
replace blackDominant=1 if country=="Colombia"
replace blackDominant=1 if country=="Brasil"
replace blackDominant=1 if country=="Nicaragua"
replace blackDominant=1 if country=="Uruguay"
replace blackDominant=1 if country=="Costa Rica"


gen indigDominant=0
replace indigDominant=1 if country=="Bolivia"
replace indigDominant=1 if country=="El Salvador"
replace indigDominant=1 if country=="Guatemala"
replace indigDominant=1 if country=="Mexico"
replace indigDominant=1 if country=="Panama"
replace indigDominant=1 if country=="Peru"
replace indigDominant=1 if country=="Chile"
replace indigDominant=1 if country=="Ecuador"
replace indigDominant=1 if country=="Honduras"

// Afro-Descendant subset

preserve
keep if dempolity>=6 & blackDominant==1

// Model 1
mixed tolr_i c.bgi_dec_fear_cent c.v2pepwrsoc_rev black indig mestizo  otroethn incum_voter cp6r edr quintile female urban [pweight=weight1500] || country: , cov(independent) || country_year:, cov(independent)
estimates store blackOnly

restore

// Indigenous subset

preserve
keep if dempolity>=6 & indigDominant==1

// Model 1
mixed tolr_i c.bgi_dec_fear_cent c.v2pepwrsoc_rev black indig mestizo  otroethn incum_voter cp6r edr quintile female urban [pweight=weight1500] || country: , cov(independent) || country_year:, cov(independent)
estimates store indigOnly

esttab indigOnly blackOnly using "table2.txt", replace tex b(3) se(3) r2(3) label alignment(.) nomtitles numbers nogaps compress title("Multi-Level Models of Tolerance Toward Regime Opponents")
restore


// Group conciousness

preserve
keep if dempolity>=6 & odd==1

// Recoding group conciousness measure

gen groupCon=0
replace groupCon=1 if rac1ca==2 & (indig==1 |black==1)

mixed tolr_i c.bgi_dec_fear_cent c.v2pepwrsoc_rev black indig mestizo  otroethn incum_voter cp6r edr quintile female urban [pweight=weight1500] || country: , cov(independent)
estimates store groupCon
esttab groupCon using "table3.txt", replace tex b(3) se(3) r2(3) label alignment(.) nomtitles numbers nogaps compress title("Multi-Level Models of Tolerance Toward Regime Opponents")

regress groupCon indig black i.pais, cluster(pais)
test indig=black
margins, atmeans at(indig=1 black=0) at(black=1 indig=0)
marginsplot, recast(bar) noci plotop(barw(.7) bc(gs10)) ///
	ytitle("Group Consciousness") xtitle("") title("") ///
	yscale(range(0(.10).70)) ylabel(0(.20).70) ///
	xlabel(1 "Indigenous" 2 "Afro-Descendant") ///
	graphregion(color(gs15))  scale(1.2)
graph save "groupConDifs.gph", replace
graph export "groupConDifs.pdf", as(pdf) replace

restore


// Including non-Democracies

use "mainData.dta", clear
merge m:1 pais year using "countryDataBase.dta", keepusing(country)
drop _merge
move country year

// Model 1
mixed tolr_i c.bgi_dec_fear_cent c.v2pepwrsoc_rev black indig mestizo otroethn incum_voter cp6r edr quintile female urban [pweight=weight1500] || country: , cov(independent) || country_year:, cov(independent)
estimates store model1

// Model 2
mixed tolr_i c.bgi_dec_fear_cent##(c.indig c.black) v2pepwrsoc_rev mestizo  otroethn incum_voter cp6r edr quintile female urban [pweight=weight1500] || country: , cov(independent) || country_year: indig black, cov(independent)
estimates store model2

// Model 3
mixed tolr_i bgi_dec_fear_cent c.v2pepwrsoc_rev##(c.indig c.black) mestizo  otroethn incum_voter cp6r edr quintile female urban [pweight=weight1500] || country: , cov(independent) || country_year: indig black, cov(independent)

estimates store model3

label var bgi_dec_fear_cent "Between Group Inequality"
label var edr "Education level"
label var otroethn "Other Ethnicity"
label var v2pepwrsoc_rev "Political Exclusion"
label var cp6r "Religious Meeting Attendance"
label var quintile "Wealth Quintile"
label var v2pepwrsoc_rev "Political Exclusion"

esttab model1 model2 model3 using "table4.txt", replace tex b(3) se(3) r2(3) label alignment(.) nomtitles numbers nogaps compress title("Multi-Level Models of Tolerance Toward Regime Opponents")



